package Network;

import Audio.AudioPlay;
import chataudio.Constant;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioFormat;

/**
 *
 * @author Romain
 */
public class ThreadServerUDP extends Thread {

    AudioPlay paudio;
    boolean running = true;
    DatagramSocket serverSocket;
    int port = 2500;

    
    /**
    *<b>Constructeur de la classe ThreadServerUDP</b><br> 
    * @param AudioFormat port
    */
    public ThreadServerUDP(AudioFormat format, int port) {
        paudio = new AudioPlay(format);
        this.port = port;
    }
    
    
    
    @Override
    public void run(){   
        try { 
            serverSocket = new DatagramSocket(port); 
            byte[] receiveData; 
  
        while(running) { 
  
          receiveData = new byte[640]; 

          DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 

          //f ( Constant.debug ) System.out.println ("Waiting for datagram packet, port: " + serverSocket.getLocalPort());
                try {
                    serverSocket.receive(receivePacket);
                } catch (IOException ex) {
                    Logger.getLogger(ThreadServerUDP.class.getName()).log(Level.SEVERE, null, ex);
                }

          //String sentence = new String(receivePacket.getData()); 
          paudio.playAudio(receivePacket.getData());      
        } 
        

     }
      catch (SocketException ex) {
          ex.printStackTrace();
        System.out.println( ex.getMessage());
        //System.exit(1);
      }
        finally 
        {
            
        serverSocket.close();
            System.out.println("close socket UDP");
        }
}
    
    
    /**
    *<b>Methode d'arret du thread</b><br> 
    */
    public void arret()
    {
        running = false;
        
        if ( ! serverSocket.isClosed() ) serverSocket.close();
    }
    
    public void pause(){
        paudio.pause();
    }
}
